package client.main.choose;

import client.advantagesuggestion.FeedbackForm;
import client.bugreport.BugReporting;
import client.common.result.Result;
import client.log.LogView;
import client.main.login.AdminLogin;
import client.material.MaterialArchiveQuery;
import client.order.AuditOrderForm;
import client.order.SubmitOrderForm;
import client.printing.AllPrinting;
import client.role.RoleList;
import client.user.UserArchiveQuery;
import remote.service.VersionService;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ExecutionException;

public class AdminChoose extends JFrame {
    private VersionService versionService = new VersionService() {
    };
    
    public AdminChoose() {
        setTitle("管理员功能选择");
        setSize(800, 600); // 调整窗口大小为800x600
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        
        setLocationRelativeTo(null);
        setResizable(false);
        String path = System.getProperty("user.dir");
        String imageAbsolutePath = path + "\\background\\image1.jpg";
        System.out.println("imageAbsolutePath: " + imageAbsolutePath);
        
        // 设置背景面板
        AdminChoose.BackgroundPanel backgroundPanel = new AdminChoose.BackgroundPanel(imageAbsolutePath); // 设置背景图片路径
        backgroundPanel.setLayout(new BoxLayout(backgroundPanel, BoxLayout.Y_AXIS)); // 垂直布局
        
        // 创建标题标签
        JLabel titleLabel = new JLabel("请选择功能", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 36)); // 更大的字体
        titleLabel.setForeground(Color.decode("#424242")); // 设置标题颜色为深灰色
        add(titleLabel, BorderLayout.NORTH);
        
        // 使用一个容器将标题标签包裹起来，以便能够在水平方向上居中
        JPanel titlePanel = new JPanel();
        titlePanel.setOpaque(false); // 设置为透明
        titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.X_AXIS)); // 横向布局
        titlePanel.add(Box.createHorizontalGlue()); // 添加左侧弹性空间
        titlePanel.add(titleLabel); // 添加标题标签
        titlePanel.add(Box.createHorizontalGlue()); // 添加右侧弹性空间
        
        backgroundPanel.add(titlePanel); // 将标题面板添加到背景面板
        backgroundPanel.add(Box.createRigidArea(new Dimension(0, 40))); // 标题与按钮之间的间距
        
        // 创建按钮面板，并设置为 GridBagLayout 布局
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridBagLayout());
        buttonPanel.setOpaque(false); // 设置面板背景透明
        
        // 定义 GridBagConstraints 对象用于布局控制
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL; // 水平方向填充
        gbc.insets = new Insets(15, 20, 15, 20); // 上、左、下、右的外边距
        
        // 创建功能按钮并添加到面板
        gbc.gridx = 0;
        gbc.gridy = 0;
        JButton UserArchiveQuery = createCustomButton("人员档案管理");
        UserArchiveQuery.addActionListener(e -> openUserArchiveQuery());
        buttonPanel.add(UserArchiveQuery, gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 0;
        JButton MaterialArchiveQuery = createCustomButton("物料档案管理");
        MaterialArchiveQuery.addActionListener(e -> openMaterialArchiveQuery());
        buttonPanel.add(MaterialArchiveQuery, gbc);
        
        // 权限管理按钮
        gbc.gridx = 2;
        gbc.gridy = 0;
        JButton RoleListUI = createCustomButton("权限管理");
        RoleListUI.addActionListener(e -> openRoleListUI());
        buttonPanel.add(RoleListUI, gbc);
        
        
        // 创建提交订单按钮
        gbc.gridx = 0;
        gbc.gridy = 1;
        JButton SubmitOrderForm = createCustomButton("提交订单");
        SubmitOrderForm.addActionListener(e -> openSubmitOrderForm());
        buttonPanel.add(SubmitOrderForm, gbc);
        
        
        gbc.gridx = 1;
        gbc.gridy = 1;
        JButton AuditOrderForm = createCustomButton("订单管理");
        AuditOrderForm.addActionListener(e -> openAuditOrderForm());
        buttonPanel.add(AuditOrderForm, gbc);
        
        gbc.gridx = 2;
        gbc.gridy = 1;
        JButton AllPrinting = createCustomButton("统计打印管理");
        AllPrinting.addActionListener(e -> openAllPrinting());
        buttonPanel.add(AllPrinting, gbc);
        
        
        // 添加查看日志文件
        gbc.gridx = 0;
        gbc.gridy = 2;
        JButton LogView = createCustomButton("查看操作日志");
        LogView.addActionListener(e -> openLogView());
        buttonPanel.add(LogView, gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 2;
        JButton BugReportDialog = createCustomButton("bug反馈");
        BugReportDialog.addActionListener(e -> openBugReportDialog());
        buttonPanel.add(BugReportDialog, gbc);
        
        
        gbc.gridx = 2;
        gbc.gridy = 2;
        JButton Advantagesuggesting = createCustomButton("优化建议");
        Advantagesuggesting.addActionListener(e -> openAdvantagesuggesting());
        buttonPanel.add(Advantagesuggesting, gbc);
        
        
        // 添加返回登录
        gbc.gridx = 1;
        gbc.gridy = 3;
        JButton AdminLogin = createCustomButton("返回登录");
        AdminLogin.addActionListener(e -> openAdminLogin());
        buttonPanel.add(AdminLogin, gbc);
        
        // 将按钮面板添加到窗口的中心
        add(buttonPanel, BorderLayout.CENTER);
        // 创建底部标签显示版本号
        JLabel versionLabel = new JLabel("版本号: " + getCurrentVersion(), SwingConstants.CENTER);
        versionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 设置字体
        versionLabel.setForeground(Color.BLACK); // 设置字体颜色为白色
        add(versionLabel, BorderLayout.SOUTH);
        // 设置窗口居中
        setLocationRelativeTo(null); // 窗口居中显示
        
        // 将按钮面板添加到背景面板
        backgroundPanel.add(buttonPanel);
        
        // 将 versionLabel 添加到 backgroundPanel
        backgroundPanel.add(versionLabel, BorderLayout.SOUTH);
        versionLabel.setOpaque(false); // 设置标签背景为透明
        
        checkForUpdates(); // 页面渲染时自动检查更新
        
        // 设置窗口可见
        setContentPane(backgroundPanel); // 设置背景面板为主内容面板
        setVisible(true);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(AdminChoose::new); // 使用 SwingUtilities 确保线程安全
    }
    
    private void checkForUpdates() {
        SwingWorker<Result, Void> worker = new SwingWorker<Result, Void>() {
            @Override
            protected Result doInBackground() throws Exception {
                String currentVersion = getCurrentVersion(); // 获取本地当前版本号
                return versionService.checkVersion(currentVersion); // 调用 checkVersion 接口
            }
            
            @Override
            protected void done() {
                try {
                    Result result = (Result) get();
                    if (result.getCode() == 200) {
                        int option = JOptionPane.showConfirmDialog(AdminChoose.this,
                                "检测到新版本，是否下载更新？",
                                "版本更新",
                                JOptionPane.YES_NO_OPTION);
                        
                        if (option == JOptionPane.YES_OPTION) {
                            downloadAndUpdate();
                        }
                    }



//                    else {
//                        JOptionPane.showMessageDialog(AdminChoose.this,
//                                "您当前使用的已是最新版本。",
//                                "版本检查",
//                                JOptionPane.INFORMATION_MESSAGE);
//                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(AdminChoose.this,
                            "检查版本时出错：",
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    private void downloadAndUpdate() {
        SwingWorker<String, Void> worker = new SwingWorker<String, Void>() {
            @Override
            protected String doInBackground() throws Exception {
                return versionService.getNewVersion();
            }
            
            @Override
            protected void done() {
                try {
                    String newVersion = get();
                    JOptionPane.showMessageDialog(AdminChoose.this,
                            "更新完成，客户端将重启。",
                            "更新成功",
                            JOptionPane.INFORMATION_MESSAGE);
                    // 创建并执行重启批处理文件
                    restartClient(newVersion);
                } catch (RuntimeException e) {
                    JOptionPane.showMessageDialog(AdminChoose.this,
                            "更新失败：",
                            "版本替换失败",
                            JOptionPane.ERROR_MESSAGE);
                } catch (InterruptedException e) {
                    JOptionPane.showMessageDialog(AdminChoose.this,
                            "更新失败：",
                            "服务器连接失败",
                            JOptionPane.ERROR_MESSAGE);
                } catch (ExecutionException e) {
                    JOptionPane.showMessageDialog(AdminChoose.this,
                            "更新失败：",
                            "服务器连接失败",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    private void restartClient(String backupExeName) {
        createRestartScript(backupExeName);
        String vbsScriptPath = System.getProperty("user.dir") + "\\restart.vbs";
        try {
            // 运行 VBS 脚本，并退出客户端
            Runtime.getRuntime().exec("wscript \"" + vbsScriptPath + "\"");
            System.exit(0);
        } catch (IOException e) {
            throw new RuntimeException("重启客户端时出错: " + e.getMessage(), e);
        }
    }
    
    private void createRestartScript(String backupExeName) {
        // 获取当前客户端目录
        String currentPath = System.getProperty("user.dir");
        String vbsScriptPath = currentPath + "\\restart.vbs";
        
        try (PrintWriter writer = new PrintWriter(new File(vbsScriptPath))) {
            writer.println("Set ws = CreateObject(\"WScript.Shell\")");
            writer.println("WScript.Sleep 2000");
            
            // 删除旧版本客户端
            writer.println("ws.Run \"cmd /c del \"\"" + currentPath + "\\warehouse-client.exe\"\"\", 0, True");
            
            // 重命名新版本文件为客户端名称
            writer.println("ws.Run \"cmd /c rename \"\"" + currentPath + "\\" + backupExeName + "\"\" \"\"warehouse-client.exe\"\"\", 0, True");
            
            // 重启客户端
            writer.println("ws.Run \"cmd /c start \"\"\"\" \"\"" + currentPath + "\\warehouse-client.exe\"\"\", 0, True");
            
        } catch (FileNotFoundException e) {
            throw new RuntimeException("无法创建重启脚本: " + e.getMessage(), e);
        }
    }
    
    private String getCurrentVersion() {
        // 从文件或配置中获取当前版本号
        return "1.0.3"; // 示例版本
    }
    
    // 创建自定义按钮的辅助方法（带圆角、渐变背景和边框效果）
    private JButton createCustomButton(String text) {
        JButton button = new JButton(text) {
            @Override
            protected void paintComponent(Graphics g) {
                if (g instanceof Graphics2D) {
                    Graphics2D g2d = (Graphics2D) g;
                    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    
                    // 设置按钮的渐变填充颜色，从淡绿色到深绿色
                    GradientPaint gradientPaint = new GradientPaint(0, 0, new Color(144, 238, 144), 0, getHeight(), new Color(34, 139, 34));
                    g2d.setPaint(gradientPaint);
                    g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30); // 设置圆角半径为30
                }
                super.paintComponent(g);
            }
            
            @Override
            protected void paintBorder(Graphics g) {
                g.setColor(new Color(21, 101, 192)); // 设置边框颜色
                ((Graphics2D) g).setStroke(new BasicStroke(2)); // 设置边框宽度
                g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 30, 30); // 圆角边框
            }
        };
        
        // 按钮的其他样式设置
        button.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        button.setForeground(Color.WHITE); // 按钮文本颜色
        button.setFocusPainted(false); // 去掉按钮焦点边框
        button.setContentAreaFilled(false); // 使按钮透明
        button.setPreferredSize(new Dimension(150, 50)); // 按钮尺寸
        button.setOpaque(false); // 按钮透明
        button.setBorderPainted(false); // 去除边框
        button.setCursor(new Cursor(Cursor.HAND_CURSOR)); // 鼠标悬停时显示手型
        
        // 鼠标悬停事件，改变按钮颜色
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent e) {
                button.setBackground(new Color(30, 136, 229)); // 鼠标悬停时背景色
                button.setForeground(new Color(255, 255, 255)); // 鼠标悬停时文本颜色
                button.setOpaque(true); // 透明度设为不透明
            }
            
            @Override
            public void mouseExited(java.awt.event.MouseEvent e) {
                button.setOpaque(false); // 鼠标离开时恢复透明度
            }
        });
        
        return button;
    }
    
    // 打开人员档案管理窗口
    private void openUserArchiveQuery() {
        new UserArchiveQuery();
    }
    
    // 打开物料档案管理窗口
    private void openMaterialArchiveQuery() {
        new MaterialArchiveQuery();
    }
    
    // 打开权限管理窗口
    private void openRoleListUI() {
        new RoleList();
    }
    
    // 打开提交订单窗口
    private void openSubmitOrderForm() {
        new SubmitOrderForm();
    }
    
    // 打开审核订单管理窗口
    private void openAuditOrderForm() {
        new AuditOrderForm();
    }
    
    // 打开统计打印管理窗口
    private void openAllPrinting() {
        new AllPrinting().setVisible(true);
    }
    
    // 打开查看日志文件窗口
    private void openLogView() {
        new LogView();
    }
    
    // 打开bug反馈窗口
    private void openBugReportDialog() {
        new BugReporting().setVisible(true);
    }
    
    // 打开优化建议窗口
    private void openAdvantagesuggesting() {
        new FeedbackForm();
    }
    
    // 打开返回登录界面的窗口
    private void openAdminLogin() {
        new AdminLogin(); // 打开 AdminLogin 窗口
        dispose(); // 关闭当前窗口
    }
    
    // 自定义背景面板类
    private static class BackgroundPanel extends JPanel {
        private Image backgroundImage;
        
        public BackgroundPanel(String imagePath) {
            try {
                backgroundImage = ImageIO.read(new File(imagePath));
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("背景图片加载失败！");
            }
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (backgroundImage != null) {
                g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
            }
        }
    }
}
